package com.dmw.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dmw.reggie.common.BaseContext;
import com.dmw.reggie.common.R;
import com.dmw.reggie.dto.OrdersDto;
import com.dmw.reggie.entity.OrderDetail;
import com.dmw.reggie.entity.Orders;
import com.dmw.reggie.service.OrderDetailService;
import com.dmw.reggie.service.OrdersService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("order")
public class OrdersController {

    @Resource
    private OrdersService ordersService;

    @Resource
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R submit(@RequestBody Orders orders){
        ordersService.submit(orders);

        return R.success(null);
    }

    @GetMapping("/userPage")
    public R<Page<OrdersDto>> userPage(Long page, Long pageSize){
        Page<Orders> pageInfo = new Page(page, pageSize);
        Page<OrdersDto> result = new Page<>(page, pageSize);

        // 获取用户id
        Long currentId = BaseContext.getCurrentId();

        // 按最近时间获取该用户的所有订单
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, currentId)
                .orderByDesc(Orders::getCheckoutTime);
        ordersService.page(pageInfo, queryWrapper);

        // 拷贝
        BeanUtils.copyProperties(pageInfo, result, "records");

        List<Orders> records = pageInfo.getRecords();
        List<OrdersDto> resultOrders = new ArrayList<>();

        records.forEach(i -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(i, ordersDto);
            // 查询订单详情
            Long orderId = i.getId();
            LambdaQueryWrapper<OrderDetail> orderDetailQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailQueryWrapper.eq(OrderDetail::getOrderId, orderId);
            List<OrderDetail> orderDetails = orderDetailService.list(orderDetailQueryWrapper);
            ordersDto.setOrderDetails(orderDetails);
            resultOrders.add(ordersDto);
        });
        result.setRecords(resultOrders);

        return R.success(result);

    }
}
